import Vue from 'vue'
// import axios from 'axios'
import { getQueryString } from '@/utils/utils'
import store from '@/store'
import { Toast } from 'vant'

let code = getQueryString('code')
let orgId = getQueryString('orgId')
let memberId = getQueryString('memberId')
let appServiceId = getQueryString('appServiceId')
let queryAppId = getQueryString('appId')

let XUserToken = getQueryString('XUserToken')
if (XUserToken) {
    localStorage.setItem('LocalXUserToken', XUserToken)
} else {
    localStorage.removeItem('LocalXUserToken')
}

// 获取url参数-用于app
// let tcode = getQueryString('code') || ''
// if (token && tcode) {
//     // 如果存在token时将code置为空，防止在main.js中又拿code去取token会报错，主要是这个code是公众号链接里的code，而非app的code
//     tcode = ''
// }
// if (tcode) {
//     sessionStorage.code = tcode
// }

// let ajaxApi = ''
// let params = null
// let method = 'Geting'
export function getBaseURL() {
    let baseUrl = ''
    try {
        let url = plus.storage.getItem('baseURL')
        if (url) {
            baseUrl = url
        }
    } catch {}
    return baseUrl
}
// export const getMenuList = async () => {
//     let pathName = location.hash.indexOf('goodsReleaseApp')
//     if (pathName === -1) return
//     // customer_service  客户管理
//     let appServiceId = 'customer_service'
//     let info = store.getters.userInfo.data
//     let orgId = info.orgId
//     let memberId = info.memberId
//     // appServiceId 拿到web端的token
//     let res = await Vue.Geting(Vue.api.getTokenByAppServiceId, { appServiceId, orgId, memberId })
//     if (res.isSuccess) {
//         let headers = {
//             'X-Access-Source': 'roc',
//             'X-Access-Token': res.data.accessToken
//         }
//         sessionStorage.accessToken = res.data.accessToken
//         // 拿到web端的appId
//         let configAppId = {
//             params: {
//                 appServiceId,
//                 orgId
//             },
//             headers
//         }
//         let getUserInfourl = `${getBaseURL()}${Vue.api.getUserInfo}`
//         let response = await axios.get(getUserInfourl, configAppId)
//         if (response.data.isSuccess) {
//             let { appId, memberId } = response.data.data
//             // 获取菜单权限
//             const params = Object.assign({ menuType: 1 }, { appId, memberId })
//             let config = {
//                 params,
//                 headers
//             }
//             let authUserResurl = `${getBaseURL()}${Vue.api.authUserRes}`
//             let resM = await axios.get(authUserResurl, config)
//             if (resM.data.isSuccess) {
//                 const d = resM.data.data
//                 getBtnAuth(d.resFuncs)
//             }
//         }
//     }
// }
// // 获取操作按钮权限
// export const getBtnAuth = (resFuncs = []) => {
//     const accessCode = {
//         goods_release_edit: false, //
//         goods_release_comein: false, //
//         goods_release_audit: false, //
//         goods_release_return: false, //
//         goods_release_del: false //
//     }
//     for (let key in accessCode) {
//         accessCode[key] = resFuncs.some((item) => item.resCode === key)
//     }
//     console.log(accessCode)
//     store.commit('setBtnsAuth', accessCode)
//     // 使用
//     //  userInfo () {
//     //     return this.$store.state.userInfo.btnsAuth || {};
//     // }
// }

export const getToken = async () => {
    if (!code && ['property', 'property_maintenance'].includes(appServiceId)) {
        let res = await Vue.Geting(Vue.api.getTokenByAppServiceId, { orgId, memberId, appServiceId })
        const token = res.data?.accessToken
        window.sessionStorage.token = token
        let userInfo = await Vue.Geting(Vue.api.getUserInfo, { accessToken: token })
        store.commit('setUserInfo', userInfo)
        setOrgIdAndMemberId(userInfo.data.orgId, userInfo.data.memberId)
    } else if (orgId && memberId) {
        // 从审批那里进来的合同详情，可以直接带着token，不用通过 code 来获取token了
        let res = await Vue.Geting(Vue.api.getAppInfoByAppServiceId, { appServiceId: 'property_maintenance', orgId })
        let appId = res.data.appId
        const tokenData = await Vue.Geting(Vue.api.appAuthorize, { memberId, orgId, appId })
        if (!tokenData.isSuccess) return
        const token = tokenData.data.accessToken
        window.sessionStorage.token = token
        let userInfo = await Vue.Geting(Vue.api.getUserInfo, { accessToken: token })
        store.commit('setUserInfo', userInfo)
        // const { appId } = userInfo.data
        setOrgIdAndMemberId(orgId, memberId)
        // await authUserRes({ appId, memberId })
    } else {
        let ajaxApi = ''
        let params = null
        let method = 'Geting'

        if (code) {
            ajaxApi = Vue.api.getToken
            params = { code }
        } else {
            ajaxApi = Vue.api.newGetToken

            let _memberId = ''
            if (memberId) {
                _memberId = memberId
            } else {
                let appUserInfo = localStorage.appUserInfo
                if (!appUserInfo) {
                    Toast('用户信息错误')
                    throw Error('用户信息错误')
                }
                appUserInfo = JSON.parse(appUserInfo)
                _memberId = appUserInfo.memberId
            }

            params = {
                appId: queryAppId,
                memberId: _memberId,
                orgId: orgId
            }
        }

        let res = null
        try {
            res = await Vue[method](ajaxApi, params)
        } catch (err) {
            if (navigator.userAgent.indexOf('Html5Plus') > 0) {
                plus.storage.getStorageSync('loginStatus', '0')
            } else {
                localStorage.setItem('loginStatus', '0')
            }
            Toast('用户信息错误,请重新进入')
            throw Error('获取token失败')
        }

        if (res.isSuccess) {
            window.sessionStorage.token = res.data.accessToken
            let userInfo = await Vue.Geting(Vue.api.getUserInfo, { accessToken: res.data.accessToken })
            store.commit('setUserInfo', userInfo)
            const { appId, memberId, orgId } = userInfo.data
            setOrgIdAndMemberId(orgId, memberId)
            // await authUserRes({ appId, memberId })
        }
    }
}

function setOrgIdAndMemberId(orgId, memberId) {
    Vue.prototype.$orgId = orgId
    Vue.prototype.$memberId = memberId
}
